<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="出发地" prop="startPlace">
        <el-input
          v-model="queryParams.startPlace"
          placeholder="请输入出发地"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="目的地" prop="endPlace">
        <el-input
          v-model="queryParams.endPlace"
          placeholder="请输入目的地"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="航空公司" prop="airlineCompanyName">
        <el-input
          v-model="queryParams.airlineCompanyName"
          placeholder="请输入航空公司"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="到达时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeEndTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:flight:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:flight:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:flight:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:flight:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="flightList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="航班ID" align="center" prop="id" />
      <el-table-column label="航班编号" align="center" prop="flightNo" />
      <el-table-column label="出发地" align="center" prop="startPlace" />
      <el-table-column label="目的地" align="center" prop="endPlace" />
      <el-table-column label="机型" align="center" prop="modelId" />
      <el-table-column label="航空公司" align="center" prop="airlineCompanyId">
        <template #default="scope">
          <dict-tag :options="passenger" :value="scope.row.airlineCompanyId" />
        </template>
      </el-table-column>
      <el-table-column
        label="出发时间"
        align="center"
        prop="startTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="到达时间"
        align="center"
        prop="endTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="price" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:flight:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:flight:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改航班信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="flightRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="航班编号" prop="flightNo">
          <el-input v-model="form.flightNo" placeholder="请输入航班编号" />
        </el-form-item>
        <el-form-item label="出发地" prop="startPlace">
          <el-input v-model="form.startPlace" placeholder="请输入出发地" />
        </el-form-item>
        <el-form-item label="目的地" prop="endPlace">
          <el-input v-model="form.endPlace" placeholder="请输入目的地" />
        </el-form-item>
        <!-- <el-form-item label="机型" prop="modelId">
          <el-input v-model="form.modelId" placeholder="请输入机型" />
        </el-form-item> -->
        <el-form-item label="机型" prop="modelId">
          <el-select v-model="form.modelId" placeholder="请选择机型">
            <el-option
              v-for="item in modelOptrions"
              :key="item.id"
              :label="item.modelName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 航空公司 -->
        <el-form-item label="航空公司" prop="airlineCompanyId">
          <el-select
            v-model="form.airlineCompanyId"
            placeholder="请选择航空公司"
          >
            <el-option
              v-for="item in airlineCompanyOptrions"
              :key="item.id"
              :label="item.airlineCompanyName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出发时间" prop="startTime">
          <el-date-picker
            clearable
            v-model="form.startTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择出发时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="到达时间" prop="endTime">
          <el-date-picker
            clearable
            v-model="form.endTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择到达时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格" />
        </el-form-item>
        <el-divider content-position="center">订单信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddOrders"
              >添加</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteOrders"
              >删除</el-button
            >
          </el-col>
        </el-row>
        <el-table
          :data="ordersList"
          :row-class-name="rowOrdersIndex"
          @selection-change="handleOrdersSelectionChange"
          ref="orders"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="序号"
            align="center"
            prop="index"
            width="50"
          />
          <el-table-column label="订单编号" prop="orderNo" width="150">
            <template #default="scope">
              <el-input
                v-model="scope.row.orderNo"
                placeholder="请输入订单编号"
              />
            </template>
          </el-table-column>
          <el-table-column label="选择舱位" prop="shipSpaceType" width="150">
            <template #default="scope">
              <el-select
                v-model="scope.row.shipSpaceType"
                placeholder="请选择选择舱位"
              >
                <el-option
                  v-for="dict in ship_space_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="选择乘机人" prop="passengerId" width="150">
            <template #default="scope">
              <el-select
                v-model="scope.row.passengerId"
                placeholder="请选择选择乘机人"
              >
                <el-option
                  v-for="dict in passenger"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="乘机人身份证"
            prop="passengerIdCard"
            width="150"
          >
            <template #default="scope">
              <el-input
                v-model="scope.row.passengerIdCard"
                placeholder="请输入乘机人身份证"
              />
            </template>
          </el-table-column>
          <el-table-column label="机建燃油" prop="engineFuel" width="150">
            <template #default="scope">
              <el-input
                v-model="scope.row.engineFuel"
                placeholder="请输入机建燃油"
              />
            </template>
          </el-table-column>
          <el-table-column label="所属航班ID" prop="flightId" width="150">
            <template #default="scope">
              <el-input
                v-model="scope.row.flightId"
                placeholder="请输入所属航班ID"
              />
            </template>
          </el-table-column>
          <el-table-column label="折后价格" prop="discountedPrice" width="150">
            <template #default="scope">
              <el-input
                v-model="scope.row.discountedPrice"
                placeholder="请输入折后价格"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Flight">
import {
  listFlight,
  getFlight,
  delFlight,
  addFlight,
  updateFlight,
} from "@/api/system/flight";
import { listAirline } from "@/api/system/airline";
import { listModel } from "@/api/system/model";

const { proxy } = getCurrentInstance();
const { passenger, ship_space_type } = proxy.useDict(
  "passenger",
  "ship_space_type"
);

const flightList = ref([]);
const ordersList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedOrders = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeEndTime = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 3,
    airlineCompanyName: null,
    startPlace: null,
    endPlace: null,
    endTime: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

/** 查询航班信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeEndTime && "" != daterangeEndTime) {
    queryParams.value.params["beginEndTime"] = daterangeEndTime.value[0];
    queryParams.value.params["endEndTime"] = daterangeEndTime.value[1];
  }
  listFlight(queryParams.value).then((response) => {
    flightList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
const airlineCompanyOptrions = ref([]);
/** 查询航空公司列表 */
function getAirlineList() {
  listAirline(queryParams.value).then((response) => {
    airlineCompanyOptrions.value = response.rows;
    console.log(airlineCompanyOptrions.value);
  });
}
const modelOptrions = ref([]);
/** 查询机型管理列表 */
function getModelList() {
  listModel(queryParams.value).then((response) => {
    modelOptrions.value = response.rows;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    flightNo: null,
    startPlace: null,
    endPlace: null,
    modelId: null,
    airlineCompanyId: null,
    startTime: null,
    endTime: null,
    price: null,
  };
  ordersList.value = [];
  proxy.resetForm("flightRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeEndTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加航班信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getFlight(_id).then((response) => {
    form.value = response.data;
    ordersList.value = response.data.ordersList;
    open.value = true;
    title.value = "修改航班信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["flightRef"].validate((valid) => {
    if (valid) {
      form.value.ordersList = ordersList.value;
      if (form.value.id != null) {
        updateFlight(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addFlight(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除航班信息编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delFlight(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 订单序号 */
function rowOrdersIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 订单添加按钮操作 */
function handleAddOrders() {
  let obj = {};
  obj.orderNo = "";
  obj.shipSpaceType = "";
  obj.passengerId = "";
  obj.passengerIdCard = "";
  obj.engineFuel = "";
  obj.flightId = "";
  obj.discountedPrice = "";
  ordersList.value.push(obj);
}

/** 订单删除按钮操作 */
function handleDeleteOrders() {
  if (checkedOrders.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的订单数据");
  } else {
    const orderss = ordersList.value;
    const checkedOrderss = checkedOrders.value;
    ordersList.value = orderss.filter(function (item) {
      return checkedOrderss.indexOf(item.index) == -1;
    });
  }
}

/** 复选框选中数据 */
function handleOrdersSelectionChange(selection) {
  checkedOrders.value = selection.map((item) => item.index);
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/flight/export",
    {
      ...queryParams.value,
    },
    `flight_${new Date().getTime()}.xlsx`
  );
}

getList();
getAirlineList();
getModelList();
</script>
